package org.sakai.service;

import org.sakai.entity.Message;
import org.sakai.entity.Result;
import org.sakai.entity.ErrorCode;
import org.sakai.mapper.MessageMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.text.SimpleDateFormat;
import java.util.*;
import java.util.Locale;

@Service
public class MessageService {
    
    @Autowired
    private MessageMapper messageMapper;
    
    private static final SimpleDateFormat DATE_FORMAT = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    
    /**
     * 格式化时间字符串，处理不同的时间格式
     * @param timeStr 时间字符串
     * @return 格式化后的时间字符串
     */
    private String formatTimeString(String timeStr) {
        if (timeStr == null || timeStr.isEmpty()) {
            return null;
        }
        
        try {
            // 如果已经是yyyy-MM-dd HH:mm:ss格式，直接返回
            if (timeStr.matches("\\d{4}-\\d{2}-\\d{2} \\d{2}:\\d{2}:\\d{2}")) {
                return timeStr;
            }
            
            // 尝试解析EEE MMM dd HH:mm:ss zzz yyyy格式（如：Thu Jun 26 22:21:07 CST 2025）
            SimpleDateFormat inputFormat = new SimpleDateFormat("EEE MMM dd HH:mm:ss zzz yyyy", Locale.ENGLISH);
            Date date = inputFormat.parse(timeStr);
            return DATE_FORMAT.format(date);
        } catch (Exception e) {
            System.err.println("时间格式转换失败: " + timeStr + ", 使用原始值");
            return timeStr;
        }
    }
    
    /**
     * 根据问诊订单ID获取聊天消息列表
     * @param consultId 问诊订单I
     * @param lastTime 最后一条消息时间
     * @return 消息列表
     */
    public Result<List<Map<String, Object>>> getChatMessageList(String consultId, String lastTime) {
        try {
            // 处理时间格式转换
            String formattedLastTime = formatTimeString(lastTime);
            
            // 获取消息列表
            List<Message> messages = messageMapper.selectMessagesByConsultId(consultId, formattedLastTime);
            
            if (!messages.isEmpty()) {
                // 转换消息格式
                List<Map<String, Object>> items = new ArrayList<>();
                for (Message msg : messages) {
                    Map<String, Object> messageItem = new HashMap<>();
                    messageItem.put("id", msg.getId());
                    messageItem.put("msgType", msg.getMsgType());
                    messageItem.put("from", msg.getFromUser());
                    messageItem.put("to", msg.getToUser());
                    messageItem.put("createdTime", DATE_FORMAT.format(msg.getCreatedTime()));
                    
                    // 构建msg对象
                    Map<String, Object> msgObj = new HashMap<>();
                    if (msg.getContent() != null) {
                        msgObj.put("content", msg.getContent());
                    }
                    if (msg.getPictureId() != null) {
                        Map<String, Object> picture = new HashMap<>();
                        picture.put("id", msg.getPictureId());
                        picture.put("url", "/consult/images/" + msg.getPictureId() + "?orderId=" + consultId);
                        msgObj.put("picture", picture);
                    }
                    
                    messageItem.put("msg", msgObj);
                    items.add(messageItem);
                }
                return Result.success(items);
            }
            return Result.success(new ArrayList<>());
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error(ErrorCode.UNKNOWN_ERROR);
        }
    }
    
    /**
     * 发送聊天消息
     * @param orderId 订单ID
     * @param msgType 消息类型
     * @param content 文本内容
     * @param pictureId 图片ID
     * @param fromUser 发送用户
     * @param toUser 接收用户
     * @return 发送结果
     */
    @Transactional
    public Result<Message> sendChatMessage(String orderId, Object msgType, String content, 
                                         String pictureId, String fromUser, String toUser) {
        try {
            Message message = new Message();
            message.setId(UUID.randomUUID().toString());
            message.setMsgType(msgType);
            message.setFromUser(fromUser);
            message.setToUser(toUser);
            message.setContent(content);
            message.setPictureId(pictureId);
            message.setConsultId(orderId);
            message.setCreatedTime(new Date());
            
            int result = messageMapper.insertSelective(message);
            if (result > 0) {
                return Result.success(message);
            } else {
                return Result.error(ErrorCode.INSERT_ERROR);
            }
        } catch (Exception e) {
            return Result.error(ErrorCode.UNKNOWN_ERROR);
        }
    }
    
    /**
     * 更新消息状态为已读
     * @param messageId 消息ID
     * @return 更新结果
     */
    @Transactional
    public Result<String> updateMessageStatus(String messageId) {
        try {
            // 查询消息是否存在
            Integer num = messageMapper.updateMessageStatus(messageId);
            // 这里可以添加已读状态的更新逻辑
            // 由于当前Message实体没有status字段，暂时返回成功
            return Result.success("消息状态更新成功");
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error(ErrorCode.UNKNOWN_ERROR);
        }
    }
    
    /**
     * 根据问诊ID获取最新消息
     * @param consultId 问诊ID
     * @return 最新消息
     */
    public Result<Message> getLatestMessage(String consultId) {
        try {
            // 由于新的方法返回Map，我们需要直接查询数据库
            // 这里可以保持原有逻辑或者重新实现
            List<Message> messages = messageMapper.selectMessagesByConsultId(consultId, null);
            if (!messages.isEmpty()) {
                // 获取最新的消息（列表已按时间排序）
                Message latestMessage = messages.get(messages.size() - 1);
                return Result.success(latestMessage);
            }
            return Result.success(null);
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error(ErrorCode.UNKNOWN_ERROR);
        }
    }
    
    /**
     * 获取用户的消息列表（会话列表）- 支持分页和排序
     * @param userId 用户ID
     * @param page 页码（从1开始）
     * @param size 每页大小
     * @param sortByUnread 是否按未读数量排序
     * @return 消息列表（包含分页信息）
     */
    public Result<Map<String, Object>> getMessageList(String userId, Integer page, Integer size, Boolean sortByUnread) {
        try {
            System.out.println("获取消息列表，用户ID: " + userId + ", 页码: " + page + ", 每页: " + size + ", 按未读排序: " + sortByUnread);
            
            // 参数校验
            if (page == null || page < 1) page = 1;
            if (size == null || size < 1) size = 10;
            if (sortByUnread == null) sortByUnread = true;
            
            // 0. 先测试简单查询
            Integer consultCount = messageMapper.testSelectConsultsByUserId(userId);
            System.out.println("用户相关的问诊数量: " + consultCount);
            
            if (consultCount == null || consultCount == 0) {
                System.out.println("没有找到会话，返回空列表");
                Map<String, Object> result = new HashMap<>();
                result.put("list", new ArrayList<>());
                result.put("total", 0);
                result.put("page", page);
                result.put("size", size);
                result.put("hasMore", false);
                return Result.success(result);
            }
            
            // 1. 获取用户的所有会话（暂时不在SQL层分页，在内存中分页）
            List<Map<String, Object>> conversations = messageMapper.selectMessageListByUserId(userId);
            System.out.println("查询到的会话数量: " + conversations.size());
            
            // 2. 为每个会话补充信息
            for (Map<String, Object> conversation : conversations) {
                String consultId = (String) conversation.get("consultId");
                String patientId = (String) conversation.get("patientId");
                String doctorId = (String) conversation.get("doctorId");
                
                // 确定对话的另一方
                String otherUserName = "Unknown";
                String otherUserAvatar = null;
                
                if (userId.equals(doctorId)) {
                    // 当前用户是医生，显示患者信息
                    Map<String, Object> patientInfo = messageMapper.selectPatientInfoById(patientId);
                    if (patientInfo != null) {
                        otherUserName = (String) patientInfo.get("name");
                        otherUserAvatar = (String) patientInfo.get("avatar");
                    }
                } else {
                    // 当前用户是患者，显示医生信息
                    Map<String, Object> doctorInfo = messageMapper.selectUserInfoById(doctorId);
                    if (doctorInfo != null) {
                        otherUserName = (String) doctorInfo.get("username");
                        otherUserAvatar = (String) doctorInfo.get("avatar");
                    }
                }
                
                conversation.put("otherUserName", otherUserName);
                conversation.put("otherUserAvatar", otherUserAvatar);
                
                // 获取最新消息
                Map<String, Object> latestMessage = messageMapper.selectLatestMessageByConsultId(consultId);
                if (latestMessage != null) {
                    conversation.put("lastMessage", latestMessage.get("content"));
                    conversation.put("lastMessageTime", latestMessage.get("lastMessageTime"));
                } else {
                    conversation.put("lastMessage", "");
                    conversation.put("lastMessageTime", conversation.get("consultCreatedTime"));
                }
                
                // 获取未读消息数量
                Integer unreadCount = messageMapper.selectUnreadMessageCountByConsultAndUser(consultId, userId);
                conversation.put("unreadCount", unreadCount != null ? unreadCount : 0);
            }
            
            // 3. 排序
            if (sortByUnread) {
                // 按未读数量倒序，未读数量相同时按时间倒序
                conversations.sort((a, b) -> {
                    Integer unreadA = (Integer) a.get("unreadCount");
                    Integer unreadB = (Integer) b.get("unreadCount");
                    if (unreadA == null) unreadA = 0;
                    if (unreadB == null) unreadB = 0;
                    
                    // 先按未读数量倒序
                    int unreadCompare = unreadB.compareTo(unreadA);
                    if (unreadCompare != 0) {
                        return unreadCompare;
                    }
                    
                    // 未读数量相同时按时间倒序
                    Object timeA = a.get("lastMessageTime");
                    Object timeB = b.get("lastMessageTime");
                    if (timeA == null && timeB == null) return 0;
                    if (timeA == null) return 1;
                    if (timeB == null) return -1;
                    return timeB.toString().compareTo(timeA.toString());
                });
            } else {
                // 仅按时间倒序
                conversations.sort((a, b) -> {
                    Object timeA = a.get("lastMessageTime");
                    Object timeB = b.get("lastMessageTime");
                    if (timeA == null && timeB == null) return 0;
                    if (timeA == null) return 1;
                    if (timeB == null) return -1;
                    return timeB.toString().compareTo(timeA.toString());
                });
            }
            
            // 4. 内存分页
            int totalCount = conversations.size();
            int startIndex = (page - 1) * size;
            int endIndex = Math.min(startIndex + size, totalCount);
            
            List<Map<String, Object>> pageData = new ArrayList<>();
            if (startIndex < totalCount) {
                pageData = conversations.subList(startIndex, endIndex);
            }
            
            // 5. 构建返回结果
            Map<String, Object> result = new HashMap<>();
            result.put("list", pageData);
            result.put("total", totalCount);
            result.put("page", page);
            result.put("size", size);
            result.put("hasMore", endIndex < totalCount);
            
            System.out.println("最终返回的会话数量: " + pageData.size() + ", 总数: " + totalCount + ", 是否还有更多: " + (endIndex < totalCount));
            return Result.success(result);
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error(ErrorCode.UNKNOWN_ERROR);
        }
    }
    
    /**
     * 获取用户头像
     * @param userId 用户ID
     * @return 头像URL
     */
    public Result<String> getUserAvatar(String userId) {
        try {
            String avatar = messageMapper.selectUserAvatarById(userId);
            return Result.success(avatar);
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error(ErrorCode.UNKNOWN_ERROR);
        }
    }
    
    /**
     * 获取用户未读消息总数
     * @param userId 用户ID
     * @return 未读消息数量
     */
    public Result<Integer> getUnreadMessageCount(String userId) {
        try {
            Integer count = messageMapper.selectUnreadMessageCountByUserId(userId);
            return Result.success(count != null ? count : 0);
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error(ErrorCode.UNKNOWN_ERROR);
        }
    }
    
    /**
     * 获取指定会话的未读消息数量
     * @param consultId 问诊ID
     * @param userId 用户ID
     * @return 未读消息数量
     */
    public Result<Integer> getUnreadMessageCountByConsult(String consultId, String userId) {
        try {
            Integer count = messageMapper.selectUnreadMessageCountByConsultAndUser(consultId, userId);
            return Result.success(count != null ? count : 0);
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error(ErrorCode.UNKNOWN_ERROR);
        }
    }
    
    /**
     * 标记指定会话的所有消息为已读
     * @param consultId 问诊ID
     * @param userId 用户ID
     * @return 操作结果
     */
    @Transactional
    public Result<String> markMessagesAsRead(String consultId, String userId) {
        try {
            Integer updatedCount = messageMapper.markMessagesAsReadByConsultAndUser(consultId, userId);
            return Result.success("已读取 " + updatedCount + " 条消息");
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error(ErrorCode.UNKNOWN_ERROR);
        }
    }
    
    /**
     * 获取会话信息（包含最新消息、未读数等）
     * @param consultId 问诊ID
     * @param userId 用户ID
     * @return 会话信息
     */
    public Result<Map<String, Object>> getConversationInfo(String consultId, String userId) {
        try {
            Map<String, Object> conversationInfo = new HashMap<>();
            
            // 获取最新消息
            Map<String, Object> latestMessage = messageMapper.selectLatestMessageByConsultId(consultId);
            if (latestMessage != null) {
                conversationInfo.put("latestMessage", latestMessage);
                conversationInfo.put("latestTime", latestMessage.get("created_time"));
            }
            
            // 获取未读消息数量
            Integer unreadCount = messageMapper.selectUnreadMessageCountByConsultAndUser(consultId, userId);
            conversationInfo.put("unreadCount", unreadCount != null ? unreadCount : 0);
            
            // 获取总消息数量
            Integer totalCount = messageMapper.countMessagesByConsultId(consultId);
            conversationInfo.put("totalCount", totalCount != null ? totalCount : 0);
            
            return Result.success(conversationInfo);
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error(ErrorCode.UNKNOWN_ERROR);
        }
    }

    /**
     * 清除用户所有未读消息
     * @param userId 用户ID
     * @return 操作结果
     */
    @Transactional
    public Result<String> clearAllUnreadMessages(String userId) {
        try {
            Integer updatedCount = messageMapper.clearAllUnreadMessagesByUser(userId);
            return Result.success("已清除 " + updatedCount + " 条未读消息");
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error(ErrorCode.UNKNOWN_ERROR);
        }
    }
}
